package ru.gelin.android.multiplier;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class OperationsHistoryAdapter extends BaseAdapter {

    Context context;
    Cursor cursor;

    public OperationsHistoryAdapter(Context context, OperationsHistory history) {
        this.context = context;
        this.cursor = history.getCursor();
    }

    @Override
    public int getCount() {
        return this.cursor.getCount();
    }

    @Override
    public Object getItem(int position) {
        return getHistoryItem(position);
    }

    OperationsHistoryItem getHistoryItem(int position) {
        this.cursor.moveToPosition(position);  //TODO optimize?
        try {
            return new OperationsHistoryItem(this.cursor);
        } catch (ParseException e) {
            return null;
        }
    }

    @Override
    public long getItemId(int position) {
        return getHistoryItem(position).date.getTime();
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = inflateView(parent);
        }
        bindView(view, getHistoryItem(position));
        return view;
    }

    View inflateView(ViewGroup parent) {
        return LayoutInflater.from(this.context).inflate(
                android.R.layout.simple_list_item_2, parent, false);
    }

    void bindView(View view, OperationsHistoryItem item) {
        String type = "";
        switch (item.operation.getType()) {     //TODO remove switch
            case MUL:
                type = this.context.getString(R.string.mul_op);
                break;
            case DIV:
                type = this.context.getString(R.string.div_op);
                break;
        }
        String text = this.context.getString(R.string.operation_history_format,
                item.operation.getNumber1(), item.operation.getNumber2(), type, item.operation.getResult());
        String date = this.context.getString(R.string.operation_history_date, item.date);

        TextView textView = (TextView)view.findViewById(android.R.id.text1);
        textView.setText(text);
        TextView dateView = (TextView)view.findViewById(android.R.id.text2);
        dateView.setText(date);
    }

}
